﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Http;
using ELearning.BLL;
using ELearning.Common.CommonStr;
using ELearning.Common.Extensions;
using ELearning.Common.Helpers;
using ELearning.Common.Model;
using ELearning.Models;
using ELearning.Models.ViewModel.YTJYAdmin.Course;

namespace ELearning.API.Controllers.YTJYAdminController
{
    /// <summary>
    /// 课程相关控制器
    /// </summary>
    public class CourseController : BaseApiController
    {
        /// <summary>
        /// 课程相关操作service
        /// </summary>
        private ECourseService eCourseService => new ECourseService();

        /// <summary>
        /// 课程视频关联操作service
        /// </summary>
        private RCourseVideoLibService rCourseVideoLibService => new RCourseVideoLibService();

        /// <summary>
        /// 课程试卷关联操作service
        /// </summary>
        private RCoursePaperService rCoursePaperService => new RCoursePaperService();

        /// <summary>
        /// 用户操作service
        /// </summary>
        private ESysUserService eSysUserService => new ESysUserService();

        /// <summary>
        /// 章节操作service
        /// </summary>
        private TChapterService tChapterService => new TChapterService();

        /// <summary>
        /// 字典操作service  
        /// </summary>
        private EDictionaryService eDictionaryService => new EDictionaryService();

        /// <summary>
        /// 获取课程表
        /// </summary>
        [HttpPost, Route("api/ytjyadmin/ECourse/GetModelList")]
        public ServiceResponse<CourseViewModel> GetModelList(CourseRequest request)
        {
            var viewModel = eCourseService.GetModelList(request);

            return ServiceResponse<CourseViewModel>.SuccessResponse(CommonConst.OprateSuccessStr, viewModel);
        }

        /// <summary>
        /// 新增或者更新信息
        /// </summary>
        [HttpPost, Route("api/ytjyadmin/ECourse/PostModel")]
        public ServiceResponse<bool> PostModel(CoursePostModel viewModel)
        {
            var model = eCourseService.Find(v => v.Id == viewModel.Id);
            if (viewModel.TeacherId == Guid.Empty)
                viewModel.TeacherId = CurrentUserModel?.UserId ?? Guid.Empty;
            if (model.IsNotNull())//编辑
            {
                model.Name = viewModel.Name;
                model.CoverUrl = viewModel.CoverUrl;
                model.CategoryId = viewModel.CategoryId;
                model.TeacherId = viewModel.TeacherId;
                model.TypeCode = viewModel.TypeCode;
                model.Description = viewModel.Description;
                model.Sort = viewModel.Sort;
                model.OldPrice = viewModel.OldPrice;
                model.NowPrice = viewModel.NowPrice;
                model.IsPublic = viewModel.IsPublic;

                model.UpdateTime = DateTime.Now;
                model.UpdateUserId = CurrentUserModel?.UserId ?? Guid.Empty;

                var deleteList = rCoursePaperService.FindList(r => !r.IsDelete && r.CourseId == model.Id).ToList();
                if (deleteList.Any())
                    rCoursePaperService.DeletesNoSaveChange(deleteList);

                if (viewModel.PaperIds.IsNotNull() && viewModel.PaperIds.Any())
                {
                    foreach (var paperId in viewModel.PaperIds)
                    {
                        var rcp = new RCoursePaper
                        {
                            Id = Guid.NewGuid(),
                            CreateTime = DateTime.Now,
                            CreateUserId = CurrentUserModel?.UserId ?? Guid.Empty,
                            UpdateTime = DateTime.Now,
                            UpdateUserId = CurrentUserModel?.UserId ?? Guid.Empty,
                            IsDelete = false,
                            PaperId = paperId,
                            CourseId = model.Id,
                            Sort = 1
                        };
                        rCoursePaperService.AddNoSaveChange(rcp);
                    }
                }

                eCourseService.Update(model);
            }
            else//新增
            {
                model = viewModel.MapTo<ECourse, CoursePostModel>();

                model.UpdateTime = DateTime.Now;
                model.UpdateUserId = CurrentUserModel?.UserId ?? Guid.Empty;

                model.CreateTime = DateTime.Now;
                model.CreateUserId = CurrentUserModel?.UserId ?? Guid.Empty;
                model.Id = Guid.NewGuid();
                model.IsUsed = true;
                model.OrgCode = CurrentUserModel?.OrgCode ?? string.Empty;

                if (viewModel.PaperIds.IsNotNull() && viewModel.PaperIds.Any())
                {
                    foreach (var paperId in viewModel.PaperIds)
                    {
                        var rcp = new RCoursePaper
                        {
                            Id = Guid.NewGuid(),
                            CreateTime = DateTime.Now,
                            CreateUserId = CurrentUserModel?.UserId ?? Guid.Empty,
                            UpdateTime = DateTime.Now,
                            UpdateUserId = CurrentUserModel?.UserId ?? Guid.Empty,
                            IsDelete = false,
                            PaperId = paperId,
                            CourseId = model.Id,
                            Sort = 1
                        };
                        rCoursePaperService.AddNoSaveChange(rcp);
                    }
                }

                eCourseService.Add(model);
            }

            return ServiceResponse<bool>.SuccessResponse(CommonConst.OprateSuccessStr, true);
        }

        /// <summary>
        /// 删除
        /// </summary>
        [HttpGet, Route("api/ytjyadmin/ECourse/DeleteModel")]
        public ServiceResponse<bool> DeleteModel(Guid id)
        {
            var model = eCourseService.Find(v => v.Id == id);

            if (model.IsNotNull())
            {
                model.IsDelete = true;
                model.UpdateTime = DateTime.Now;
                model.UpdateUserId = CurrentUserModel?.UserId ?? Guid.Empty;
                eCourseService.Update(model);
            }

            return ServiceResponse<bool>.SuccessResponse(CommonConst.OprateSuccessStr, true);
        }

        /// <summary>
        /// 获取课程关联或者不关联的视频列表
        /// </summary>
        [HttpPost, Route("api/ytjyadmin/ECourse/GetCourseVideoList")]
        public ServiceResponse<CourseVideoViewModel> GetCourseVideoList(CourseVideoRequest request)
        {
            var viewModel = eCourseService.GetCourseVideoList(request);

            return ServiceResponse<CourseVideoViewModel>.SuccessResponse(CommonConst.OprateSuccessStr, viewModel);
        }

        /// <summary>
        /// 保存课程关联或者不关联的视频
        /// </summary>
        [HttpPost, Route("api/ytjyadmin/ECourse/CourseVideoPost")]
        public ServiceResponse<bool> CourseVideoPost(CourseVideoPostModel request)
        {
            if (request.Type == 0)//要进行关联操作
            {
                if (request.VideoIdList.Any())
                {
                    var addList = new List<RCourseVideoLib>();
                    foreach (var id in request.VideoIdList)
                    {
                        var addModel = new RCourseVideoLib
                        {
                            Id = Guid.NewGuid(),
                            CourseId = request.CourseId,
                            CreateUserId = CurrentUserModel.UserId,
                            CreateTime = DateTime.Now,
                            IsDelete = false,
                            Sort = 0,
                            UpdateTime = DateTime.Now,
                            UpdateUserId = CurrentUserModel.UserId,
                            VideoLibId = id
                        };
                        addList.Add(addModel);
                    }
                    if (addList.Any())
                    {
                        var dt = addList.ToDataTable(null);
                        dt.TableName = "RCourseVideoLib";
                        SqlBulkCopyHelper.SaveTable(dt);
                    }
                }
            }
            else//要进行取消关联操作
            {
                if (request.VideoIdList.Any())
                {
                    var deleteList = rCourseVideoLibService.FindList(r => !r.IsDelete && r.CourseId == request.CourseId && request.VideoIdList.Contains(r.VideoLibId)).ToList();
                    if (deleteList.Any())
                    {
                        foreach (var d in deleteList)
                        {
                            d.IsDelete = true;
                            d.UpdateTime = DateTime.Now;
                            d.UpdateUserId = CurrentUserModel.UserId;
                            rCourseVideoLibService.UpdateNoSaveChange(d);
                        }

                        rCourseVideoLibService.SaveChange();
                    }
                }
            }

            return ServiceResponse<bool>.SuccessResponse(CommonConst.OprateSuccessStr, true);
        }

        /// <summary>
        /// 获取讲师列表
        /// </summary>
        [HttpGet, Route("api/ytjyadmin/ECourse/GetTeacherList")]
        public ServiceResponse<object> GetTeacherList()
        {
            var orgCode = CurrentUserModel?.OrgCode ?? CommonConst.DEFAULT_ORGCODE;
            var viewModel = eSysUserService.FindList(u => !u.IsDelete && u.UserType == UserType.UserTypeTEACHER && u.OrgCode == orgCode).Select(u => new { value = u.UserID, label = u.UserName }).ToList();

            return ServiceResponse<object>.SuccessResponse(CommonConst.OprateSuccessStr, viewModel);
        }

        /// <summary>
        /// 导入课程
        /// </summary>
        [HttpPost, Route("api/Student/ImportCourse")]
        public object ImportCourse()
        {
            var result = CommonConst.UploadFailDefaultUrl;
            var filelist = HttpContext.Current.Request.Files;
            var models = new List<ImportCourseViewModel>();
            var path = HttpContext.Current.Server.MapPath("/ImportConfig/importCourseConfig.xml");
            var xr = XMLHelper.ReadToHashtable(path);
            if (filelist.Count > 0)
            {
                for (var i = 0; i < filelist.Count; i++)
                {
                    var file = filelist[i];
                    var fileName = file.FileName;
                    var fn = fileName.Split('\\');
                    if (fn.Length > 1)
                    {
                        fileName = fn[fn.Length - 1];
                    }
                    DataTable dataTable = null;
                    var fs = fileName.Split('.');
                    if (fs.Length > 1)
                    {
                        var ext = fs[fs.Length - 1];
                        if (ext == "xlsx")
                            dataTable = ExcelHelp.ExcelToTableForXLSX(file.InputStream, xr.ImportHashtable, true); //excel转成datatable
                        else
                            dataTable = ExcelHelp.ExcelToTableForXLS(file.InputStream); //excel转成datatable
                    }
                    //users = dataTable.ToDataList<InsertSGMWAdminUsersViewModel>(); //datatable转成list
                    models = dataTable.ToDataList<ImportCourseViewModel>(); //datatable转成list
                }
            }

            var faile = new List<ImportCourseViewModel>();
            var exportList = new List<ImportCourseViewModel>();
            var dics = eDictionaryService.FindList(d => !d.IsDelete).ToList();
            var categroy = dics.FirstOrDefault(d => d.TypeCode == DictionaryConst.CATEGORY_CODE);
            var categorys = dics.Where(d => d.ParentID == categroy?.ID).ToList();

            var cls = dics.FirstOrDefault(d => d.TypeCode == DictionaryConst.CLASS_TYPE_CODE);
            var clss = dics.Where(d => d.ParentID == cls?.ID).ToList();

            var users = eSysUserService.FindList(x => !x.IsDelete && x.OrgCode == CurrentUserModel.OrgCode).ToList();

            var saves = new List<SaveCourseModel>();
            //数据list转成数据库实体对应的list
            foreach (var m in models)
            {
                if (string.IsNullOrEmpty(m.Name) || string.IsNullOrEmpty(m.CategoryName) || string.IsNullOrEmpty(m.TypeName))
                {
                    m.Reason = "课程名称/类型名称/班级类型必填";
                    faile.Add(m);
                    exportList.Add(m);
                    continue;
                }

                var ca = categorys.FirstOrDefault(x => x.TypeName == m.CategoryName.Trim());
                if (ca.IsNull())
                {
                    m.Reason = "类型名称不存在，请确认后重新上传！";
                    faile.Add(m);
                    exportList.Add(m);
                    continue;
                }

                var ct = clss.FirstOrDefault(x => x.TypeName == m.TypeName.Trim());
                if (ct.IsNull())
                {
                    m.Reason = "班级类型不存在，请确认后重新上传！";
                    faile.Add(m);
                    exportList.Add(m);
                    continue;
                }

                var it = saves.FirstOrDefault(x => x.Name == m.Name);
                if (it.IsNull())
                {
                    var c = new SaveCourseModel
                    {
                        Name = m.Name,
                        CategoryName = m.CategoryName,
                        CategoryId = ca.TypeCode,
                        TypeCode = ct.TypeCode,
                        TypeName = m.TypeName,
                        Description = m.Description,
                        TeacherName = m.TeacherName
                    };

                    if (!string.IsNullOrEmpty(m.ChapterName))
                        c.ChapterNames.Add(m.ChapterName);
                    saves.Add(c);
                }
            }

            //构造保存数据库的实体
            var succeECourse = new List<ECourse>();
            var succeChapter = new List<TChapter>();
            foreach (var courseModel in saves)
            {
                var user = users.FirstOrDefault(x => x.UserName == courseModel.TeacherName);
                var course = new ECourse
                {
                    Id = Guid.NewGuid(),
                    CategoryId = courseModel.CategoryId,
                    CreateTime = DateTime.Now,
                    CreateUserId = CurrentUserModel.UserId,
                    CoverUrl = CommonConst.DEFAULT_COURSE_COVER_URL,
                    Description = courseModel.Description,
                    IsDelete = false,
                    IsPublic = false,
                    IsUsed = true,
                    Name = courseModel.Name,
                    OrgCode = CurrentUserModel.OrgCode,
                    UpdateTime = DateTime.Now,
                    UpdateUserId = CurrentUserModel.UserId,
                    Sort = 0,
                    TypeCode = courseModel.TypeCode,
                    TeacherId = user?.UserID ?? Guid.Empty,
                    NowPrice = 0,
                    OldPrice = 0
                };

                if (courseModel.ChapterNames.Any())
                {
                    foreach (var chapterName in courseModel.ChapterNames)
                    {
                        var chapter = new TChapter
                        {
                            UpdateTime = DateTime.Now,
                            UpdateUserId = CurrentUserModel.UserId,
                            CreateTime = DateTime.Now,
                            CreateUserId = CurrentUserModel.UserId,
                            Id = Guid.NewGuid(),
                            CourseId = course.Id,
                            Description = chapterName,
                            IsDelete = false,
                            Name = chapterName,
                            OrgCode = course.OrgCode,
                            Sort = 0,
                            PassGrade = 0
                        };
                        succeChapter.Add(chapter);
                    }
                }

                succeECourse.Add(course);
            }

            //批量保存课程
            if (succeECourse.Any())
            {
                var dt = succeECourse.ToDataTable(null);
                dt.TableName = "ECourse";
                SqlBulkCopyHelper.SaveTable(dt);
            }

            //批量保存章节
            if (succeChapter.Any())
            {
                var dt = succeChapter.ToDataTable(null);
                dt.TableName = "TChapter";
                SqlBulkCopyHelper.SaveTable(dt);
            }

            var url = string.Empty;
            if (exportList.Any())
            {
                var extDt = exportList.ToDataTable(xr.ExportHashtable);
                var str = GetSavePath();
                var strs = str.Split(',');
                if (strs.Any() && strs.Length > 1)
                {
                    var fileFullPath = strs[0];
                    url = PictureHelper.GetFileFullPath(strs[1]);
                    ExcelHelp.TableToExcelForXLSX(extDt, fileFullPath);
                }
            }

            var list = new { failed = faile.Take(100).ToList(), failedCount = faile.Count }; //数据太多的话，浏览器会崩溃

            if (!exportList.Any())
            {
                var json = new { list, msg = "添加成功", url };
                return ServiceResponse<object>.SuccessResponse(json);
            }
            else
            {
                var json = new { list, msg = "添加失败", url };
                return ServiceResponse<object>.SuccessResponse(CommonConst.OprateFailStr, json);
            }
        }

    }
}